import { defineStore } from 'pinia'
import axios from 'axios'
import type { SceneTrainingPlan, TrainingPage } from '@/types/training'

export const useTrainingStore = defineStore('training', {
  state: () => ({
    currentPlan: null as SceneTrainingPlan | null,
    isLoading: false,
  }),

  getters: {
    sceneName: (state) => state.currentPlan?.sceneName ?? '',
    currentIndex: (state) => state.currentPlan?.currentPageIndex ?? 0,
    totalPages: (state) => state.currentPlan?.pages?.length ?? 0,
  },

  actions: {
    async fetchSceneTrainingPlan(sceneId: string) {
      console.log('Starting to fetch training plan for scene:', sceneId)
      this.isLoading = true
      try {
        // 调用实际的API
        const response = await axios.post(`/api/plan/train/${sceneId}`)
        console.log('API response:', response.data)

        // 假设API返回的数据结构符合SceneTrainingPlan类型
        const plan: SceneTrainingPlan = response.data

        console.log('Setting current plan:', plan)
        this.currentPlan = plan
        console.log('Current plan:', this.currentPlan)
      } catch (error) {
        console.error('获取训练计划失败:', error)
        throw error
      } finally {
        this.isLoading = false
        console.log('Finished fetching training plan')
      }
    },

    updatePageCompletion(pageId: string, completed: boolean) {
      if (!this.currentPlan) return

      const page = this.currentPlan.pages.find((p) => p.id === pageId)
      if (page) {
        page.completed = completed
        // 检查是否所有页面都已完成
        const allCompleted = this.currentPlan.pages.every((p) => p.completed)
        if (allCompleted) {
          this.currentPlan.completed = true
        }
      }
    },

    getCurrentPage(): TrainingPage | null {
      if (!this.currentPlan) return null
      return this.currentPlan.pages[this.currentPlan.currentPageIndex]
    },

    moveToNextPage() {
      if (!this.currentPlan) return false
      if (this.currentPlan.currentPageIndex < this.currentPlan.pages.length - 1) {
        this.currentPlan.currentPageIndex++
        return true
      }
      return false
    },

    moveToPreviousPage() {
      if (!this.currentPlan) return false
      if (this.currentPlan.currentPageIndex > 0) {
        this.currentPlan.currentPageIndex--
        return true
      }
      return false
    },
  },
})
